package cn.edu.ctbu.web.controller;

import cn.edu.ctbu.web.domain.Teacher;
import cn.edu.ctbu.web.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    /**
     * 验证登录信息
     * @param request HttpServletRequest对象
     * @return 如果验证失败返回重定向字符串，否则返回null
     */
    private String validateLogin(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if(session.getAttribute("userid") == null){
            return "redirect:/login";
        }
        String loginNo = (String) session.getAttribute("loginno");
        Teacher validTeacher = teacherService.findByNo(loginNo);
        if (validTeacher == null) {
            return "redirect:/login";
        }
        return null;
    }

    /**
     * 登录后显示首页，若未登录强行进入main，会被重定向至登录页面
     * @return login.html 或 /teacher/main
     */
    @RequestMapping("main")
    public String list(HttpServletRequest request, Model model){
        String redirectUrl = validateLogin(request);
        if (redirectUrl != null) {
            return redirectUrl;
        }
        List<Teacher> teachers = teacherService.findAllTeacher();
        model.addAttribute("data", teachers);
        return "/teacher/main";
    }

    /**
     * 显示首页
     * @return index.html 或 重定向到登录页面
     */
    @GetMapping("index")
    public String index(HttpServletRequest request){
        String redirectUrl = validateLogin(request);
        if (redirectUrl != null) {
            return redirectUrl;
        }
        return "/teacher/index";
    }

    /**
     * 显示课程表
     * @return course.html 或 重定向到登录页面
     */
    @GetMapping("course")
    public String course(HttpServletRequest request){
        String redirectUrl = validateLogin(request);
        if (redirectUrl != null) {
            return redirectUrl;
        }
        return "/teacher/course";
    }

    /**
     * 显示成绩表
     * @return grade.html 或 重定向到登录页面
     */
    @GetMapping("/grade")
    public String grade(HttpServletRequest request){
        String redirectUrl = validateLogin(request);
        if (redirectUrl != null) {
            return redirectUrl;
        }
        return "/teacher/grade";
    }
}